'use strict';

import {
    View,
    TouchableOpacity,
    Navigator,
    Text,
    Image,
    ListView,
    SegmentedControlIOS,
    AlertIOS,
    StyleSheet,
    ActivityIndicator
} from 'react-native';
import React from 'react';	
import URL from '../config/server';
import {Utils} from '../config/utils';
import Footer from '../component/Footer';


var NavigationBarRouteMapper = {
    LeftButton(route, navigator, index, navState) {
        return null;
    },
    RightButton(route, navigator, index, navState) {
        return null;
    },
    _onValueChange: function (value) {
        this.navigator.parentNavigator.replace({
            id: 'News'
        })
    },
    Title(route, navigator, index, navState) {
        return (
            <View style={{alignItems:'center',justifyContent:'center'}}>
                <SegmentedControlIOS
                    navigator={navigator}
                    style={styles.newstitle}
                    tintColor="#ffffff"
                    selectedIndex={1}
                    onValueChange={this._onValueChange}
                    values={['通知','新闻']}/>
            </View>
        );
    }
};


export default class News extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2
            }),
            loaded: false,
            loadMore: true,
            pagesize: 10
        };
    }

    componentDidMount() {
        this._InfoisUnmounted = false;
        this.fetchData();
    }

    componentWillUnmount() {
        this._InfoisUnmounted = true;
    }

    fetchData() {
        var that = this;

        //这里配置调用后台的url
        var API_URL = URL.local + 'note/';
        var PARAMS = '2/1/' + this.state.pagesize;
        var REQUEST_URL = API_URL + PARAMS;
        fetch(REQUEST_URL)
            .then((response) => response.json())
            .then((responseData) => {
            	console.log(responseData)
                if (!that._InfoisUnmounted) {
                    if (responseData.length >= this.state.pagesize) {
                        this.setState({
                            dataSource: this.state.dataSource.cloneWithRows(responseData),
                            loaded: true
                        });
                    } else {
                        this.setState({
                            dataSource: this.state.dataSource.cloneWithRows(responseData),
                            loaded: true,
                            loadMore: false
                        });
                    }
                }
            }).catch(function (e) {
                if (e.message.indexOf('length') >= 0) {
                    that.setState({
                        loadMore: false
                    });
                    return
                }
                AlertIOS.alert(
                    '温馨提示',
                    '网络连接错误，请关闭飞行模式或检查您的网络连接。'
                )
            })
            .done();
    }

    toContent(id) {
        this.props.navigator.push({
            id: 'Content',
            message: {
                mid: id,
                mtype: 2
            }
        });
    }

    handleEnd() {
        var temp = this.state.pagesize;
        this.setState({
            pagesize: this.state.pagesize + 10,
            loadMore: true
        })
        this.fetchData()
    }

    _renderFooter() {
        if (this.state.loadMore) {
            return (
                <View style={styles.footerload}>
                    <ActivityIndicator
                        animating={true}
                        style={{justifyContent:'center'}}
                    />
                    <Text>
                        加载数据...
                    </Text>
                </View>
            )
        } else {
            return null;
        }
    }

    reload() {
        return this.fetchData()
    }

    renderScene() {
        if (!this.state.loaded) {
            return this.renderLoadingView();
        }
        return (
            <View style={styles.container}>
                <ListView
                    style={styles.contentView}
                    dataSource={this.state.dataSource}
                    renderRow={this.renderMovie.bind(this)}
                    removeClippedSubviews={true}
                    minBetweenTime={2000}
                    loadData={this.reload.bind(this)}
                    onEndReached={this.handleEnd.bind(this)}
                    onEndReachedThreshold={-10}
                    renderFooter={this._renderFooter.bind(this)}
                />
                <View style={styles.down}>
                    <Footer navigator={this.props.navigator} current={'Info'}/>
                </View>
            </View>
        );
    }

    renderLoadingView() {
        return (
            <View style={styles.container}>
                <View style={styles.listView}>
                    <Text style={styles.centerText}>
                        正在加载数据，请稍后...
                    </Text>
                </View>
                <View style={styles.down}>
                    <Footer navigator={this.props.navigator} current={'Info'}/>
                </View>
            </View>
        );
    }

    renderMovie(item) {
        return (
            <TouchableOpacity onPress={()=>{this.toContent(item.id)}}>
                <View style={styles.Items}>
                    <Image
                        source={{uri:item.image==''?"asdfasdf":item.image}}
                        style={styles.thumbnail}
                    />
                    <View style={styles.rightContainer}>
                        <Text style={styles.title}>{item.title}</Text>
                        <Text style={styles.mtitle}>{item.byzd1}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        );
    }

    render() {
        return (
            <Navigator
                renderScene={this.renderScene.bind(this)}
                navigator={this.props.navigator}
                message={this.props.message}
                navigationBar={
                    <Navigator.NavigationBar
                        style={{backgroundColor: '#e02820', alignItems: 'center'}}
                        routeMapper={NavigationBarRouteMapper} />
                }
            />
        );
    }
}

const styles = StyleSheet.create({
    container: {
        marginTop: 64,
        flex: 1,
        backgroundColor: '#ffffff'
    },
    newstitle: {
        marginTop: 5,
        height: 30,
        width: 200
    },
    Items: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        padding: 3,
        backgroundColor: '#f5f5f9',
        borderBottomWidth: 0.5,
        borderColor: '#dddddd'
    },
    footerload: {
        height: 30,
        justifyContent: 'center',
        alignItems: 'center',
        flexDirection: 'row'
    },
    contentView: {
        flex: 1,
        backgroundColor: '#f5f5f9'
    },
    listView: {
        flex: 1,
        backgroundColor: '#f5f5f9',
        justifyContent: 'center',
        alignItems: 'center'
    },
    down: {
        height:44,
        backgroundColor: '#000000',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center'
    },
    bottomText: {
        flex: 1,
        color: '#ffffff',
        textAlign: 'center',
        fontSize: 16
    },
    rightContainer: {
        flex: 1,
        height: 70,
        justifyContent: 'flex-start'
    },
    title: {
        fontSize: 15,
        marginBottom: 8,
        textAlign: 'left'
    },
    mtitle: {
        fontSize: 13,
        color: '#a9a9a9',
        textAlign: 'left'
    },
    thumbnail: {
        width: 100,
        height: 70,
        marginRight: 3,
        resizeMode: Image.resizeMode.stretch
    },
    noticeItem: {
        flex: 1,
        padding: 5,
        flexDirection: 'row',
        borderBottomColor: '#eeeeee',
        borderBottomWidth: 1,
        backgroundColor: '#ffffff'
    },
    //左侧推广图标
    Tuiguang: {
        fontSize: 13,
        borderWidth: 1,
        borderColor: '#e02820',
        color: '#e02820',
        textAlign: 'center',
        borderRadius: 5,
        width: 40,
        height: 25,
        alignSelf: 'center',
        paddingTop: 6,
        marginRight: 5
    },
    //右侧信息
    goodInfo: {
        flex: 1
    },
    goodTit: {
        fontSize: 15,
        fontWeight: '600',
        color: '#000000',
        textAlign: 'left',
        marginTop: 5,
        marginBottom: 5,
        marginRight: 10
    },
    //详情的样式
    main: {
        marginTop: 64,
        flex: 1,
        width:Utils.size.width
    },
    mcontainer:{
        flex:1
    },
    centerText: {
        fontSize: 18
    }
});